package com.sec.bnjey.activity;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.sec.bnjey.BaseActivity;
import com.sec.bnjey.R;
import com.sec.bnjey.activity.dialog.IKPopup;
import com.sec.bnjey.activity.dialog.IKPopup.Builder.onIKPopupClickListener;
import com.sec.bnjey.bluetooth.BtService;
import com.sec.bnjey.bluetooth.OBDListener;
import com.sec.bnjey.database.DbUtil;
import com.sec.bnjey.database.DiagDbAdapter;
import com.sec.bnjey.database.DtcDbAdapter;
import com.sec.bnjey.global.Global;
import com.sec.bnjey.global.GlobalApplication;
import com.sec.bnjey.svc.DaemonService;
import com.sec.bnjey.utils.RbLog;
import com.sec.bnjey.utils.Utils;

public class MainActivity extends BaseActivity implements OnClickListener,
		OBDListener {

	private static final String TAG = "MainActivity";

	private ProgressDialog mProgressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		RbLog.d(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainactivity);

		mSyncHandler.sendEmptyMessage(0);

	}

	private boolean isDaemoServiceRunning() {
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if ("com.bnjey.vtalk.svc.DaemonService".equals(service.service
					.getClassName())) {
				return true;
			}
		}
		return false;
	}

	Handler mSyncHandler = new Handler() {

		public void handleMessage(Message msg) {

			RbLog.d(TAG, "mSyncHandler " + msg.what);

			switch (msg.what) {
			case 0:
				mProgressDialog = ProgressDialog.show(MainActivity.this, "",
						"loading...", true);

				// start progress
				Intent intent = new Intent(MainActivity.this,
						DaemonService.class);
				intent.putExtra("startFromMain", true);
				startService(intent);

				// for timeout
				mSyncHandler.sendEmptyMessageDelayed(1, 2000);
				break;

			// timeout check.
			case 1:

				if (isDaemoServiceRunning() == false) {
					mSyncHandler.sendEmptyMessageDelayed(2, 1000);
				} else {
					mSyncHandler.sendEmptyMessageDelayed(1, 1000);
				}

				break;

			case 2:
				// song todo end progress
				mProgressDialog.dismiss();
				break;

			default:
				break;
			}

		}

		@Override
		public void dispatchMessage(Message msg) {
			// TODO Auto-generated method stub
			super.dispatchMessage(msg);
		};

	};

	@Override
	protected void onDestroy() {
		RbLog.d(TAG, "onDestroy");

		BtService.getBtService().disconnect();
		// disable bluetooth
		if (GlobalApplication.getBluetoothOldStatus() == false) {
			// BtService.getBtService().disable(); //alex
		}

		DiagDbAdapter.getInstance(GlobalApplication.getAppContext()).close();
		DtcDbAdapter.getInstance(GlobalApplication.getAppContext()).close();

		super.onDestroy();

	}

	@Override
	protected void onResume() {
		RbLog.d(TAG, "onResume");
		initialize();

		super.onResume();
	}

	private void popupError() {

		final IKPopup.Builder popup = new IKPopup.Builder(this,
				IKPopup.POPUP_INFO_TWO_BTN, getString(R.string.popup_title),
				getString(R.string.popup_error_communication),
				getString(R.string.btn_yes), getString(R.string.btn_no));

		final Dialog dlg = popup.create();
		popup.setOnIKPopuoClickListener(new onIKPopupClickListener() {
			@Override
			public void onIKPopUpClick(View v) {
				switch (v.getId()) {
				case R.id.B_Popup_Ok:
					dlg.dismiss();
					Intent intentBluetooth = new Intent();
					intentBluetooth
							.setAction(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
					intentBluetooth.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intentBluetooth);
					break;
				case R.id.B_Popup_Cancel:
					dlg.dismiss();
					break;
				}
			}
		});
		dlg.setCancelable(false);
		dlg.show();
	}

	public static boolean downloadFile(String downUrl, String outFilePath) {

		try {
			URL url = new URL(downUrl);
			// URL url = new URL("http", "http://ingkor.hanatech.net/firmware/",
			// 80, "Vtalk.bin/");

			URLConnection conexion = url.openConnection();

			int lenghtOfFile = conexion.getContentLength();
			InputStream input = url.openStream();

			OutputStream output = new FileOutputStream(outFilePath);

			int count;
			byte data[] = new byte[1024];

			while ((count = input.read(data)) != -1) {
				output.write(data, 0, count);
			}

			output.flush();
			output.close();
			input.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	protected void onPause() {
		RbLog.d(TAG, "onPause");
		super.onPause();

	}

	@Override
	protected void onRestart() {
		RbLog.d(TAG, "onRestart");
		super.onRestart();
	}

	@Override
	protected void onStart() {
		RbLog.d(TAG, "onStart");
		super.onStart();
	}

	@Override
	protected void onStop() {
		RbLog.d(TAG, "onStop");
		super.onStop();
	}

	private void initialize() {

		Button b;
		b = (Button) findViewById(R.id.B_TopMenu_Left);
		b.setVisibility(View.GONE);

		TextView tv = (TextView) findViewById(R.id.TV_TopMenu_SelectedCar);

		// get selected car name
		String selectedCarName = Global
				.getSelectedCarName(getString(R.string.setting_register_unregistered));

		if (selectedCarName
				.equals(getString(R.string.setting_register_unregistered))) {
		}
		tv.setText("[ " + selectedCarName + " ]");
		tv.setVisibility(View.GONE);

		ImageView iv = (ImageView) findViewById(R.id.IV_TopMenu_Title);
		iv.setBackgroundResource(R.drawable.main_top_logo);

		b = (Button) findViewById(R.id.B_Main_CarCheck);
		b.setOnClickListener(this);
		b = (Button) findViewById(R.id.B_Main_BlackBox);
		b.setOnClickListener(this);
		b = (Button) findViewById(R.id.B_Main_EcoDrive);
		b.setOnClickListener(this);
		b = (Button) findViewById(R.id.B_Main_ReapairShop);
		b.setOnClickListener(this);

		b = (Button) findViewById(R.id.B_Main_Supplies);

		b = (Button) findViewById(R.id.B_BottomMenu_Help);
		b.setOnClickListener(this);
		b = (Button) findViewById(R.id.B_BottomMenu_Setting);
		b.setOnClickListener(this);

		iv = (ImageView) findViewById(R.id.B_BottomMenu_Logo);
		iv.setVisibility(View.VISIBLE);

		updateTopMenuIcons();
		// copy data base from asset if db does not exist in local file system
		DbUtil.copyDB(getApplicationContext(), "dtc_info.db");

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.B_TopMenu_Left:
			break;

		case R.id.B_Main_CarCheck:

			popupCarCheck();

			break;

		case R.id.B_Main_BlackBox:

			if (Utils.getAvailableExternalMemorySize() < 100000000) {
				showTimeoutDialog4();
			} else {

				String gs = android.provider.Settings.Secure
						.getString(
								getContentResolver(),
								android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

				if (!gs.contains("gps")) {
					Intent gpsOptionsIntent = new Intent(
							android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
					startActivity(gpsOptionsIntent);
				} else {
					// startActivity(new Intent(MainActivity.this,
					// BlackBoxActivity.class));
					// overridePendingTransition(0, 0);
				}

			}

			break;

		case R.id.B_Main_EcoDrive:

			// new
			startActivity(new Intent(MainActivity.this,
					NewMileageActivity.class));
			overridePendingTransition(0, 0);

			break;

		case R.id.B_Main_ReapairShop:

			// startActivity(new Intent(MainActivity.this,
			// RepairShopActivity.class));
			// overridePendingTransition(0, 0);

			break;

		case R.id.B_Main_Supplies:

			// startActivity(new Intent(MainActivity.this,
			// SuppliesActivity.class));
			// overridePendingTransition(0, 0);
			break;

		case R.id.B_BottomMenu_Help:

			// startActivity(new Intent(MainActivity.this, HelpActivity.class));
			// overridePendingTransition(0, 0);
			break;

		case R.id.B_BottomMenu_Setting:

			// startActivity(new Intent(MainActivity.this,
			// SettingActivity.class));
			// overridePendingTransition(0, 0);
			break;
		}
	}

	private void AMCommand(String command) {
		try {
			RbLog.d(TAG, "AMCommand:" + command);
			Runtime.getRuntime().exec(command);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

	}

	// private void showTimeoutDialog() {
	//
	// final IKPopup.Builder popup = new IKPopup.Builder(MainActivity.this,
	// IKPopup.POPUP_ALERT_ONE_BTN,
	// getString(R.string.popup_type_information),
	// getString(R.string.popup_sync), getString(R.string.btn_ok),
	// getString(R.string.btn_no));
	// final Dialog dlg = popup.create();
	// popup.setOnIKPopuoClickListener(new onIKPopupClickListener() {
	// @Override
	// public void onIKPopUpClick(View v) {
	// switch (v.getId()) {
	// case R.id.B_Popup_Ok:
	// startActivity(new Intent(MainActivity.this,
	// NewMileageActivity.class));
	//
	// overridePendingTransition(0, 0);
	// dlg.dismiss();
	// break;
	// case R.id.B_Popup_Cancel:
	// dlg.dismiss();
	// break;
	// }
	// }
	// });
	// dlg.setCancelable(false);
	// dlg.show();
	// }

	private void showTimeoutDialog2() {

		final IKPopup.Builder popup = new IKPopup.Builder(MainActivity.this,
				IKPopup.POPUP_ALERT_ONE_BTN,
				getString(R.string.popup_type_information),
				getString(R.string.popup_sync), getString(R.string.btn_ok),
				getString(R.string.btn_no));
		final Dialog dlg = popup.create();
		popup.setOnIKPopuoClickListener(new onIKPopupClickListener() {
			@Override
			public void onIKPopUpClick(View v) {
				switch (v.getId()) {
				case R.id.B_Popup_Ok:
					dlg.dismiss();
					break;
				case R.id.B_Popup_Cancel:
					dlg.dismiss();
					break;
				}
			}
		});
		dlg.setCancelable(false);
		dlg.show();
	}

	private void popupCarCheck() {

		final IKPopup.Builder popup = new IKPopup.Builder(MainActivity.this,
				IKPopup.POPUP_ALERT_ONE_BTN, "알아두기",
				"고장진단기능은 자동차의 시동On(차키를 1/2만 돌리는상태)일때 정상반응합니다",
				getString(R.string.btn_ok), getString(R.string.btn_no));

		final Dialog dlg = popup.create();

		popup.setOnIKPopuoClickListener(new onIKPopupClickListener() {
			@Override
			public void onIKPopUpClick(View v) {
				switch (v.getId()) {
				case R.id.B_Popup_Ok:

					BtService.getBtService().OBD_Request(
							BtService.OBD_GET_COMMUNICATION_START, null,
							MainActivity.this);

					dlg.dismiss();
					break;
				}
			}
		});
		dlg.setCancelable(false);
		dlg.show();
	}

	private void showTimeoutDialog4() {

		final IKPopup.Builder popup = new IKPopup.Builder(MainActivity.this,
				IKPopup.POPUP_ALERT_ONE_BTN,
				getString(R.string.popup_type_information),
				getString(R.string.popup_bb_storage),
				getString(R.string.btn_yes), getString(R.string.btn_no));
		final Dialog dlg = popup.create();
		popup.setOnIKPopuoClickListener(new onIKPopupClickListener() {
			@Override
			public void onIKPopUpClick(View v) {
				switch (v.getId()) {
				case R.id.B_Popup_Ok:

					dlg.dismiss();
					break;
				case R.id.B_Popup_Cancel:
					dlg.dismiss();
					break;
				}
			}
		});
		dlg.setCancelable(false);
		dlg.show();
	}

	@Override
	public void onOBDEvent(int type, Object retObject) {
		// TODO Auto-generated method stub

	}

	// private void showVersionDialog() {
	//
	// final IKPopup.Builder popup = new IKPopup.Builder(
	// MainActivity.this,
	// IKPopup.POPUP_ALERT_TWO_BTN,
	// getString(R.string.popup_type_information),
	// "새로운 버전이 추가 되었습니다 \n 업그레이드를 하시겠습니까? \n(업그레이드를 하지 않을시 오작동 할 가능성이 있습니다)",
	// getString(R.string.btn_yes), getString(R.string.btn_no));
	// final Dialog dlg = popup.create();
	// popup.setOnIKPopuoClickListener(new onIKPopupClickListener() {
	// @Override
	// public void onIKPopUpClick(View v) {
	// switch (v.getId()) {
	// case R.id.B_Popup_Ok:
	// startActivity(new Intent(MainActivity.this,
	// FirmwareActivity.class));
	// overridePendingTransition(0, 0);
	// dlg.dismiss();
	// break;
	// case R.id.B_Popup_Cancel:
	//
	// dlg.dismiss();
	// break;
	// }
	// }
	// });
	// dlg.setCancelable(false);
	// dlg.show();
	// }

	// @Override
	// public void onBackPressed() {
	//
	// if (HistoryBackUtil.onBackPressed(this) == true) {
	// BtService.getBtService().stop();
	// finish();
	// }
	// }

	// @Override
	// public void onOBDEvent(int type, Object retObject) {
	// Log.e(TAG, "onOBDEvent");
	//
	// byte[] data = (byte[]) retObject;
	// if (data == null) {
	// Log.e(TAG, "onOBDEvent ret data is Null, Type:" + type);
	// }
	//
	// switch (type) {
	// case BtService.OBD_GET_COMMUNICATION_START:
	//
	// RbDialog dlg = new RbDialog(this, RbDialog.TITLE, "not response");
	//
	// if (data != null && (data[0] == 4 || data[0] == 3 || data[0] == -1)) {
	// showTimeoutDialog2();
	// } else {
	// startActivity(new Intent(MainActivity.this, DiagActivity.class));
	// overridePendingTransition(0, 0);
	// }
	// break;
	//
	// default:
	// break;
	// }
	//
	// }
}